<?php if( ! defined('ABSPATH')) exit('restricted access');



/**

 * WPnukes Admin Panel

 *

 * An open source wordpress themes options admin panel

 *

 * @package		WPnukes Apanel

 * @author		WPnukes team <info@wpnukes.com>

 * @copyright	Copyright 2012 © Fourthwave technologies, (PVT) Limited. - All rights reserved

 * @license		http://wpnukes.com/admin_panel/license.html

 * @website		http://wpnukes.com

 * @since		Version 1.0

 */



if(!class_exists('WP_List_Table'))

{

	include(ABSPATH.'/wp-admin/includes/class-wp-list-table.php');

}



class appointment_List_Table extends WP_List_Table

{	

	var $_args = array('per_page'=>20, 'singular'=>'appointment_list_table', 'plural' =>'appointments_list_table','ajax'=>false, 'screen'=>null);

	private $text_domain = '';

	

	function __construct($options = array(), $text_domain)

	{

		$this->text_domain = $text_domain;

		

		$this->screen = convert_to_screen( $this->_args['screen'] );

		

		//Appointment form

		if($options)

		{

			if(isset($_GET['create']) || (isset($_GET['id']) && is_numeric($_GET['id']))) $this->form($options);

			else $this->appointment_list();

		}

	}

	

		

	/** Add new appointment */

	function form($options)

	{

		global $wpdb;



		$this->_webnukes = &$GLOBALS['_webnukes']; /** Clone the fw_base_class object */

		$this->_webnukes->load('html_class', '', true); /** Load WPnukes HTML class */

		$this->_webnukes->load('wp_html_class','html'); /** Load wordpress HTML class */

		

		/** Edit mode */

		$edit_mode = (isset($_GET['id']) && is_numeric($_GET['id'])) ? $_GET['id'] : '';

				

		/** User permission or appointment validation */

		if($edit_mode)

		{

			if(current_user_can('create_users'))

				$query = "SELECT * FROM ".$wpdb->prefix."appointments WHERE ID = '".$edit_mode."'";

			else

				$query = "SELECT * FROM ".$wpdb->prefix."appointments WHERE ID = '".$edit_mode."' AND requested_phy = '".get_current_user_id()."'";

			

			if( ! $settings = $wpdb->get_row($query, ARRAY_A))

			{

				$this->_webnukes->msg->adminMessage( __('You don\'t have permission to edit this appointment or it\'s deleted.', $this->text_domain) );

				die();

			}

			/** Delete Request */

			if(isset($_GET['delete']))

			{

				//verify nonunce

				if( ! wp_verify_nonce($_REQUEST['_wpnonce'], 'bulk-appointments')) wp_die( __('You don\'t have permission to delete this appointment', $this->text_domain) );

				

				$wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."appointments WHERE ID = %d", $edit_mode));

				$this->_webnukes->msg->adminMessage( __('The appointment has been deleted successfully', $this->text_domain), 'update');

				$this->appointment_list();

			}

		}



		if(count($_POST))

		{

		

			foreach($options as $k=>$v)

			{

				$this->_webnukes->validation->set_rules($k, $v['label'], $v['validation']);

			}



			if($this->_webnukes->validation->run() !== false)

			{

				$settings = array();

				foreach($options as $k=>$v)

				{

					$settings[$k] = $this->_webnukes->validation->post($k);

				}



				if($edit_mode)

				{

					$GLOBALS['wpdb']->update($GLOBALS['wpdb']->prefix.'appointments', $settings, array('ID' => $edit_mode));

					$this->_webnukes->msg->adminMessage( __('The appointment has been updated successfully', $this->text_domain), 'updated' );

				}else

				{

					$GLOBALS['wpdb']->insert($GLOBALS['wpdb']->prefix.'appointments', $settings);

					$this->_webnukes->msg->adminMessage( __('The new appointment has been added successfully', $this->text_domain), 'updated' );

				}

			}

		}



		$data = array();

		foreach($options as $k=>$v)

		{

			$value = (isset($settings[$k])) ? $settings : array($k => $v['std']);

			$data['fields'][$k] = $this->_webnukes->html->generator($k, $v, $value, 'array');

		}

		

		$content = $this->_webnukes->html->layout('wp_admin/form_table', $data, true);

		$this->_webnukes->html->layout('wp_admin/wrap', array('action'=>'admin.php?'.$_SERVER['QUERY_STRING'],'content'=>$content,'nonce_action'=>'appointment','nonce_name'=>'nukes_appointment'));



		/** Clear the data variable to reduce the load on memory */

		$this->data = array();

		

		$label = ($edit_mode) ? __('Edit Appointment', $this->text_domain) : __('Add new appointment', $this->text_domain);

		echo '<div class="wrap"><div class="icon32 icon32-posts-post" id="icon-edit"><br></div><h2>'.$label.'</h2>';

		echo $GLOBALS['_webnukes']->html->build();

		echo '</div>';

	}

	

	function appointment_list()

	{

		echo '<div class="wrap">

		<div class="icon32 icon32-posts-post" id="icon-edit"><br>

		</div><h2>'.__('Appointments', $this->text_domain).'<a class="add-new-h2" href="'.add_query_arg(array('page' =>$_GET['page'],'create'=>'new'), $GLOBALS['pagenow']).'">'.__('Add New', $this->text_domain).'</a></h2>';

		

		$this->prepare_items();

		

		//echo '<form method="post"><input type="hidden" name="page" value="nukes_doctors" />';

		//$this->search_box('search', 'search_id');

		//echo '</form>';

		

		$this->display();

		echo '</div>';

		die();

	}

	

	/** Get the columns list */

	function get_columns()

	{

		

		if(current_user_role() == 'doctors')

		$columns = array(

						//'cb'=>'<input type="checkbox" />',

						'patient_name'=> __('Patient Name', $this->text_domain),

						'app_type'=> __('for', $this->text_domain),

						'app_gender'=> __('Gender', $this->text_domain),

						'location'=> __('Location', $this->text_domain),

						'status'=> __('Status', $this->text_domain),

						);

		else

			$columns = array(

						//'cb'=>'<input type="checkbox" />',

						'patient_name'=> __('Patient Name', $this->text_domain),

						'doctor_name'=>__('Doctor Name', $this->text_domain),

						'app_type'=> __('for', $this->text_domain),

						'app_gender'=> __('Gender', $this->text_domain),

						'location'=> __('Location', $this->text_domain),

						'status'=> __('Status', $this->text_domain),

						);

		return $columns;

    }

	

	/** Prepare Items */

    function prepare_items()

	{

		/** Get Columns for top and bottom */

		$columns = $this->get_columns();



		/** Hidden Columns List */

		$hidden = array();



		/** Sortable Columns list */

		$sortable = $this->get_sortable_columns();

		$this->_column_headers = array($columns, $hidden, $sortable);



		$this->items = $GLOBALS['wpdb']->get_results($this->get_query());



		/** Pagination Support */

		$this->set_pagination_args(array(

											'total_items' => count($this->items), //WE have to calculate the total number of items

											'per_page' => $this->_args['per_page'] //WE have to determine how many items to show on a page

											)

									);

    }

	

	/** Default Column view */

	/** Wordpress looks for column_COLUMNNAME for custom styling */

    function column_default($item, $column_name)

	{

		switch($column_name)

		{

			case "location" : 

					return $item->app_city.', '.$item->app_state;

				break;

			default : 

					return $item->$column_name;

				break;

		}

    }

	

	/** Sortable Columns list */

    function get_sortable_columns()

	{

		if(current_user_role() == 'doctors')

			$columns =  array(

			'patient_name' => array('patient_name',false),

			//'doctor_name' => array('doctor_names',false),

			'app_gender' => array('app_gender', false),

			'app_city' => array('app_city', false),

			'app_state' => array('app_state', false),

			'status' => array('status', false),

			);

		else

			$columns =  array(

			'patient_name' => array('patient_name',false),

			'doctor_name' => array('doctor_name',false),

			'app_gender' => array('app_gender', false),

			'app_city' => array('app_city', false),

			'app_state' => array('app_state', false),

			'status' => array('status', false),

			);

		return $columns;

    }

	

	/** Get query */

    function get_query()

	{

		global $wpdb;



		$query = "SELECT a.*,b.display_name as doctor_name FROM ".$wpdb->prefix."appointments as a INNER JOIN ".$wpdb->prefix."users as b ON a.requested_phy = b.ID";

		

		$query .= (current_user_role() == 'doctors') ? " WHERE b.ID = '".get_current_user_id()."'" : '';

		

		/** If no sort, default to title */

		$query .= ( ! empty( $_GET['orderby'] ) ) ? ' order by a.'.$wpdb->escape($_GET['orderby']) : ' order by a.status';

		

		/** If no order, default to asc */

		$this->_args['order'] = (empty($_GET['order'] ) || $_GET['order'] == 'asc') ? 'asc' : 'desc';

		$query .= ' '.$this->_args['order'];



		$this->_args['number'] = isset($this->_args['number']) ? $this->_args['number'] : 1;

		/** Offset */

		$query .= ' LIMIT '.($this->get_pagenum() - 1) * $this->_args['number'].', '.$this->_args['per_page'];

		

		return $query;

    }

	

	/** Custom column view */

    function column_patient_name($item)

	{

		$actions = array(

						'edit' => '<a href="'.add_query_arg(array('id'=>$item->ID)).'">'. __('Edit') .'</a>',

						'delete' => "<a class='submitdelete' href='" . wp_nonce_url( add_query_arg(array('id'=>$item->ID,'delete'=>'true'))."", 'bulk-appointments' ) . "'>" . __( 'Delete' ) . "</a>",

					);

					

		return sprintf('%1$s %2$s', '<strong>'.$item->patient_name.'</strong>', $this->row_actions($actions) );

    }

	

	function column_status($item)

	{

		switch($item->status)

		{

			case "1" :

				return __("Accepted", $this->text_domain);

			break;

			case "2" :

				return __("Rejected", $this->text_domain);

			break;

			default :

				return __("Pending", $this->text_domain);

			break;

		}

	}

	

	/** Bulk Action Support */

    function get_bulk_actions()

	{

		return array();

		$actions = array('delete' => __('Delete', $this->text_domain));

		return $actions;

    }

	

	/** Checkbox support */

    function column_cb($item)

	{

		return sprintf(

		'<input type="checkbox" name="appointments[]" value="%s" />', $item->ID

		);

    }

	

	/** No item message */

    function no_items()

	{

    	_e('No appointment found', $this->text_domain);

    }

}